import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.codec.binary.Base64;
import org.json.JSONException;
import org.json.JSONObject;

public class QueryExecutor {
	public static int totalMatches(String host, String category, String keyWord)
			throws IOException, JSONException {
		File f = new File("cache.txt");
		if (f.exists()) {
			try {
				FileInputStream fstream = new FileInputStream("cache.txt");
				DataInputStream in = new DataInputStream(fstream);
				BufferedReader br = new BufferedReader(
						new InputStreamReader(in));
				String strLine;
				while ((strLine = br.readLine()) != null) {
					if (strLine.equals(host + " " + category + " " + keyWord)) {
						String result = br.readLine();
						br.close();
						return Integer.parseInt(result.split(" ", 2)[0]);
					}
				}
				br.close();
			} catch (Exception e) {// Catch exception if any
				System.err.println("Error: " + e.getMessage());
			}
		}
		return executeQuery(host, category, keyWord);

	}

	private static int executeQuery(String host, String category, String keyWord)
			throws IOException, JSONException {
		String bingUrlBef = "https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/v1/Composite?Query=%27";
		String bingUrlSite = "site%3a" + host;
		String[] keyWordSep = keyWord.split(" ");
		String bingUrlMid = "";
		for (int i = 0; i < keyWordSep.length; i++)
			bingUrlMid = bingUrlMid + "%20" + keyWordSep[i];

		String bingUrlAft = "%27&$top=4&$format=Json";

		// Provide your account key here.
		String accountKey = "g8MIzS0dlBDoWFt1069DkhomL/LhZrv/hZGqu/E03aA=";

		byte[] accountKeyBytes = Base64
				.encodeBase64((accountKey + ":" + accountKey).getBytes());
		String accountKeyEnc = new String(accountKeyBytes);

		URL url = new URL(bingUrlBef + bingUrlSite + bingUrlMid + bingUrlAft);
		URLConnection urlConnection = url.openConnection();
		urlConnection.setRequestProperty("Authorization", "Basic "
				+ accountKeyEnc);

		InputStream inputStream = (InputStream) urlConnection.getContent();
		byte[] contentRaw = new byte[urlConnection.getContentLength()];
		inputStream.read(contentRaw);
		String content = new String(contentRaw);

		/*
		 * if (keyWord.equals("java") && !keyWord.equals("calories fat") &&
		 * !keyWord.equals("radiation treatment") &&
		 * !keyWord.equals("eating fat")) {
		 */
		// System.out.println(content);
		try {
			JSONObject myjson = new JSONObject(content);
			JSONObject the_json_object = myjson.getJSONObject("d")
					.getJSONArray("results").getJSONObject(0);
			int resultMatches = the_json_object.getInt("WebTotal");
			String[] resultUrl = new String[4];
			for (int i = 0; i < the_json_object.getJSONArray("Web").length(); i++) {
				resultUrl[i] = the_json_object.getJSONArray("Web")
						.getJSONObject(i).getString("Url");
			}

			writeFile(host, category, keyWord, resultMatches, resultUrl);
			return resultMatches;
		} catch (JSONException e) {
			return 0;
		}

	}

	private static void writeFile(String host, String category, String keyWord,
			int resultMatches, String[] resultUrl) {
		// TODO Auto-generated method stub
		try {
			// format host keyWord
			// format resultMatches resultUrl[0] resultUrl[1] ..
			// Create file
			BufferedWriter out = new BufferedWriter(new FileWriter("cache.txt",
					true));
			out.write(host + " " + category + " " + keyWord + "\n");
			String url = "";
			for (int i = 0; i < 4; i++) {
				if (resultUrl[i] != null)
					url = url + resultUrl[i] + " ";

			}
			out.write(resultMatches + " " + url + "\n");
			// Close the output stream
			out.close();
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}

	}

	public static String topFourUrl(String host, String category, String keyWord) {
		File f = new File("cache.txt");
		if (f.exists()) {
			try {
				FileInputStream fstream = new FileInputStream("cache.txt");
				DataInputStream in = new DataInputStream(fstream);
				BufferedReader br = new BufferedReader(
						new InputStreamReader(in));
				String strLine;
				while ((strLine = br.readLine()) != null) {
					if (strLine.equals(host + " " + category + " " + keyWord)) {
						String result = br.readLine();
						br.close();
						return result.split(" ", 2)[1];
					}
				}
				br.close();
			} catch (Exception e) {// Catch exception if any
				System.err.println("Error: " + e.getMessage());
			}
		}
		return null;
	}

	/*
	 * public static void main(String[] arg) throws IOException, JSONException{
	 * executeQuery("diabetes.org", "computers", "java"); }
	 */

}
